from flask import Flask, render_template, request, jsonify, Response, stream_with_context, make_response
from chatbot_graph import ChatBotGraph
import json
import logging
import sys
from datetime import datetime

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('app.log'),
        logging.StreamHandler(sys.stdout)
    ]
)
logger = logging.getLogger(__name__)

app = Flask(__name__)
handler = ChatBotGraph()

@app.route('/')
def home():
    logger.info("访问首页")
    return render_template('index.html')

@app.route('/ask', methods=['GET', 'POST'])
def ask():
    try:
        # 获取请求方法
        method = request.method
        logger.info(f"收到{method}请求: {request.url}")
        
        # 获取问题
        if method == 'POST':
            question = request.form.get('question')
        else:  # GET
            question = request.args.get('question')
            
        if not question:
            logger.warning("未收到问题")
            return jsonify({'answer': '抱歉，我没有理解您的问题'})

        logger.info(f"问题: {question}")
        
        # 检查是否请求流式输出
        stream = request.args.get('stream', 'false').lower() == 'true'
        logger.info(f"流式输出: {stream}")
        
        if stream:
            def generate():
                try:
                    print("开始生成流式响应")
                    for chunk in handler.chat_main(question, stream=True):
                        if chunk:
                            #print(f"生成回答片段: {chunk}")
                            yield f"data: {json.dumps({'answer': chunk})}\n\n"
                except Exception as e:
                    logger.error(f"生成回答时出错: {str(e)}")
                    print(f"生成回答时出错: {str(e)}")
                    yield f"data: {json.dumps({'error': str(e)})}\n\n"
            
            print("创建流式响应")
            response = make_response(stream_with_context(generate()))
            response.headers['Content-Type'] = 'text/event-stream'

            response.headers['Cache-Control'] = 'no-cache'
            response.headers['Connection'] = 'keep-alive'
            response.headers['X-Accel-Buffering'] = 'no'
            print("返回流式响应")
            return response
        else:
            # 非流式输出
            try:
                answer = handler.chat_main(question, stream=False)
                logger.info(f"生成回答: {answer}")
                return jsonify({'answer': answer})
            except Exception as e:
                logger.error(f"生成回答时出错: {str(e)}")
                return jsonify({'error': str(e)})
                
    except Exception as e:
        logger.error(f"处理请求时出错: {str(e)}")
        return jsonify({'error': str(e)})

if __name__ == '__main__':
    logger.info("启动服务器...")
    app.run(debug=True, host='0.0.0.0', port=5000)